import argparse
import os
import re
import sys
from collections.abc import Iterable


def parse_cmd(config_dict):
    parser = argparse.ArgumentParser(
        prog="auto_file_tidy",
        description="tidy your messy files quickly",
        epilog="by wowo-hala"
    )

    parser.add_argument("-d","--dirPath", required=False, help="same as [dir_path] option")
    parser.add_argument("--sep", help="same as [sep] option")
    parser.add_argument("-px","--prefix",action="store_true", required=False, help="same as [classify:prefix] option")
    parser.add_argument('-sx', '--suffix',action="store_true", required=False,help="same as [classify:suffix] option")
    parser.add_argument('-cfp', '--configFilePath', required=False, help="custom configuration file path suffix must be '.configure'")
    parser.add_argument('-c', '--configFile', action="store_true", required=False, help="create configuration file template")
    args = parser.parse_args()
    cmd_dict = {}
    if args.dirPath:
        cmd_dict['dir_path'] = os.path.abspath(args.dirPath)
    if  args.sep:
        cmd_dict['sep'] = args.sep
    if args.prefix:
        cmd_dict['classify:prefix'] = args.prefix
    if args.suffix:
        cmd_dict['classify:suffix'] = args.suffix
    if args.configFilePath:
        if os.path.splitext(args.configFile)[-1] != ".configure":
            print("suffix error: require suffix '.configure'")
            sys.exit(1)
        abs_config_file_path = os.path.abspath(args.configFile)
        cmd_dict['config_file_path'] = abs_config_file_path

    if args.configFile:
        # maybe current without save
        if cmd_dict.get('config_file_path'):
             abs_config_file_path = cmd_dict['config_file_path']
        else:
             abs_config_file_path = config_dict['config_file_path']
        abs_config_dir_path = os.path.split(abs_config_file_path)[0]
        if not os.path.exists(abs_config_dir_path):
            os.mkdir(abs_config_dir_path)
        with open(abs_config_file_path, 'a') as wfp:
            wfp.write('# ================ Auto File Tidy Configure =======================\n')
            for option, value in config_dict.items():
                wfp.write(f"{option} = ")
                if isinstance(value, list):
                    value_format = "("
                    for subValue in value:
                        value_format += str(subValue) + ','
                    value_format += ")\n"
                    wfp.write(value_format)
                else:
                    wfp.write(str(value)+'\n')



    return cmd_dict


